package com.binge.test8;

import java.io.*;
import java.util.*;

public class SqlSplitter {

    public static void main(String[] args) throws IOException {
        String inputFile = "/Users/bin/Desktop/a.sql";  // 输入文件
        String outputFile = "/Users/bin/Desktop/b.sql"; // 输出文件
        int batchSize = 100;  // 每批次的插入数量

        // 读取输入文件
        List<String> sqlLines = readFile(inputFile);

        // 拆分SQL并写入输出文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
            StringBuilder currentSql = new StringBuilder();
            int valuesCount = 0;

            for (String line : sqlLines) {
                if (line.startsWith("INSERT INTO")) {
                    // 如果是新的INSERT语句，先写入前一批次的SQL
                    if (valuesCount > 0) {
                        currentSql.append(");");
                        writer.write(currentSql.toString());
                        writer.newLine();
                    }
                    currentSql = new StringBuilder(line); // 开始新的INSERT语句
                    valuesCount = 0;
                } else if (line.startsWith("VALUES")) {
                    // 拼接VALUES语句
                    if (valuesCount > 0) {
                        currentSql.append(",");
                    }
                    currentSql.append(line);
                    valuesCount++;

                    // 如果VALUES达到100条，输出并重置
                    if (valuesCount >= batchSize) {
                        currentSql.append(");");
                        writer.write(currentSql.toString());
                        writer.newLine();
                        currentSql = new StringBuilder("INSERT INTO ainemo.libra_conference_number (id, enabled, display_name, expire_time, conference_number_type, permanent, number) VALUES ");
                        valuesCount = 0;
                    }
                }
            }

            // 写入最后剩余的SQL
            if (valuesCount > 0) {
                currentSql.append(");");
                writer.write(currentSql.toString());
                writer.newLine();
            }
        }

        System.out.println("拆分完成，结果已写入 " + outputFile);
    }

    // 读取文件内容
    private static List<String> readFile(String inputFile) throws IOException {
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }
        return lines;
    }
}
